<?
require_once(dirname(__FILE__).'/../models/ShippingServices.php');

class ShippingServicesController extends Main_Controller_Action {	
	public function preDispatch()
    {
        if (!unserialize(Zend_Auth::getInstance()->getIdentity())->getIsAdministrator()) {        
                $this->_helper->redirector('', '');
        } else {
           /**
			 * Translation - Loading dictionaries common and backoffice_common
			 */
			$commonLocale = Translator::loadTranslation($this->currentLang, 'common');
			$this->view->commonLocale = $commonLocale;
        }
    }
    
	function indexAction(){
		try{
				$services = ModelMapper::instance('ShippingServices')->findAll();
		} catch (DatabaseException $e){
				$e->getMessage();
		}
			
		$this->view->services = $services;
	}
	
	function addAction(){
		$this->view->uploadDestination = $this->config->uploads->shippingServices->origin_dir;
		$this->view->fileTypesId = $this->config->uploads->shippingServices->fileTypesId;
		
		$smarty = $this->view->getEngine();
		$tpl = $smarty->fetch('shipping-services/add.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function editAction(){
		$service = ModelMapper::instance('ShippingServices')->find(intval($this->getRequest()->getParam('shippingServicesId')));
		
		$smarty = $this->view->getEngine();
		
		$this->view->uploadDestination = $this->config->uploads->shippingServices->origin_dir;
		$this->view->fileTypesId = $this->config->uploads->shippingServices->fileTypesId;
		$this->view->service = $service;
		$tpl = $smarty->fetch('shipping-services/edit.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function saveAction(){
		//Database::instance()->getConn()->debug = 1;
		$formData = $this->_request->getParam('addForm');
		
		//debug($formData);
		if (intval($formData['shippingServicesId']) >0) {
			$obj = ModelMapper::instance('ShippingServices')->find(intval($formData['shippingServicesId']));
			$mainImageId = $obj->getMainImageId();
		}
		else {
			$obj = new ShippingServices();
			$mainImageId = NULL;
		}
		
		$obj->setService(trim(strip_tags(stripcslashes($formData['service']))));
		$obj->setDescription(trim(strip_tags(stripcslashes($formData['description']))));
		$obj->setPrice(number_format(str_ireplace(',','.',$formData['price']), 2,'.', ''));
		if (intval($formData['filesId']) != 0){
			if ($mainImageId != NULL && $mainImageId != intval($formData['filesId'])){
				$file = ModelMapper::instance('Files')->find($mainImageId);
				$file->delete();
				/**
				 * TODO UNLINK FILE
				 */
				//unlink($mainImageId);
			}
			
			$obj->setMainImageId(intval($formData['filesId']));
		} else 
			$obj->setMainImageId($mainImageId);		
		
		exit();
	}
	
	
}

	
?>
